package com.lenovo.spider.htmlrender

import io.ktor.application.Application
import io.ktor.application.call
import io.ktor.application.install
import io.ktor.application.log
import io.ktor.content.resources
import io.ktor.content.static
import io.ktor.features.CallLogging
import io.ktor.features.DefaultHeaders
import io.ktor.http.ContentType.Text.Html
import io.ktor.response.respondText
import io.ktor.routing.Routing
import io.ktor.routing.get
import io.ktor.server.engine.embeddedServer
import io.ktor.server.netty.Netty

/**
 *
 * @author <a href="mailto: 393803588@qq.com">刘涵(Hanl)</a>
 * By 2018/1/17
 */

fun Application.module() {
    install(DefaultHeaders)
    install(CallLogging)
    install(Routing) {
        get("/") { call.respondText("Welcome") }
        get("/render") {
            val url = call.request.queryParameters["url"]
            val waitTime = call.request.queryParameters["waitTime"]
            val locator = call.request.queryParameters["locator"]
            val eventType = call.request.queryParameters["eventType"]
            log.debug("Got: [url: $url, waitTime: $waitTime, eventType: $eventType \n locator: $locator]")
            renderHtml(url, waitTime = waitTime as? Double, eventType = eventType, locator = locator).apply {
                call.respondText(this, Html)
            }
        }
        static("static") {
            resources("static")
        }
    }
}


fun main(args: Array<String>) {
    embeddedServer(Netty, 8080, module = Application::module)
            .start()
}